// src/background/toggle.ts - 统一的侧边栏切换逻辑
// 严格遵循文档要求的同步链处理，避免用户手势丢失

/** 记录每个 Tab 侧栏状态（true = 已开） */
const panelState = new Map<number, boolean>();

/**
 * 获取侧边栏状态
 */
export function getSidebarStatus(tabId: number): boolean {
  return panelState.get(tabId) ?? false;
}

/**
 * 设置侧边栏状态
 */
export function setSidebarStatus(tabId: number, isOpen: boolean): void {
  panelState.set(tabId, isOpen);
  console.log(`[Toggle] Tab ${tabId} sidebar state: ${isOpen ? 'open' : 'closed'}`);
}

/**
 * 统一的侧边栏切换逻辑
 * 关键：使用同步链处理，不使用await，保持用户手势
 */
export function toggleSidePanel(tabId: number): void {
  console.log(`[Toggle] Processing toggle request for tab ${tabId}`);

  try {
    const isOpen = getSidebarStatus(tabId);
    console.log(`[Toggle] Current state: ${isOpen ? 'open' : 'closed'}`);

    if (isOpen) {
      // 关闭侧边栏：同步调用，不使用await
      chrome.sidePanel.setOptions({
        tabId,
        enabled: false
      });
      setSidebarStatus(tabId, false);
      console.log(`[Toggle] ✅ Side panel closed for tab ${tabId}`);

      // 延迟重新启用，允许将来的打开操作
      setTimeout(() => {
        chrome.sidePanel.setOptions({
          tabId,
          enabled: true
        }).catch(err => {
          console.warn(`[Toggle] Re-enable failed for tab ${tabId}:`, err);
        });
      }, 300);
    } else {
      // 打开侧边栏：同步调用，不使用await
      chrome.sidePanel.setOptions({
        tabId,
        path: 'src/sidepanel/sidepanel.html',
        enabled: true
      });

      // 同步调用open，用catch处理错误而不是await
      chrome.sidePanel.open({ tabId }).catch(err => {
        console.warn(`[Toggle] Side panel open failed for tab ${tabId}:`, err);
      });

      setSidebarStatus(tabId, true);
      console.log(`[Toggle] ✅ Side panel opened for tab ${tabId}`);
    }
  } catch (error) {
    console.error(`[Toggle] Error during toggle for tab ${tabId}:`, error);
  }
}

/**
 * 清理标签页状态
 */
export function cleanupTabState(tabId: number): void {
  panelState.delete(tabId);
  console.log(`[Toggle] Cleaned up state for tab ${tabId}`);
}

/**
 * 重置标签页状态（页面刷新时）
 */
export function resetTabState(tabId: number): void {
  setSidebarStatus(tabId, false);
  console.log(`[Toggle] Reset state for tab ${tabId}`);
}